package com.feng.security.service.impl;

import com.feng.common.api.ResultCode;
import com.feng.common.utils.Asserts;
import com.feng.mbg.domain.SysPermission;
import com.feng.mbg.domain.SysUser;
import com.feng.mbg.domain.SysUserExample;
import com.feng.mbg.mapper.SysUserMapper;
import com.feng.security.config.SecurityConst;
import com.feng.security.domain.LoginUser;
import com.feng.system.dao.SysPermissionDao;
import com.feng.system.dao.SysRoleDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Feng
 * @since 2022/4/17 21:04
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysPermissionDao permissionDao;

    @Autowired
    private SysRoleDao roleDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        SysUserExample userExample = new SysUserExample();
        userExample.createCriteria().andUsernameEqualTo(username).andIsDeletedEqualTo(0);
        List<SysUser> resUsers = userMapper.selectByExample(userExample);
        // 如果查询不到数据就通过抛出异常来给出提示
        if (resUsers.isEmpty()) {
            Asserts.fail(ResultCode.USERNAME_PWD_ERROR);
        }
        SysUser user = resUsers.get(0);
        Long userId = user.getUserId();
        // 获取用户的角色等级
        Integer level = roleDao.selectMinLevelByUserId(userId);
        int roleLevel = level == null ? SecurityConst.ROLE_LEVEL_MAX_VALUE : level;
        // 根据用户查询权限信息 添加到LoginUser中
        List<SysPermission> sysPermissions = permissionDao.selectByUserId(user.getUserId());
        ArrayList<String> permissions = new ArrayList<>();
        for (SysPermission sysPermission : sysPermissions) {
            permissions.add(sysPermission.getPermissionKey());
        }
        //封装成UserDetails对象返回
        return new LoginUser(user, roleLevel, permissions);
    }
}
